<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

class Sale extends Base
{
    public function index()
    {
        if (request()->isAjax()) {

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            $where['status'] = ['EQ', 3];

            if (!in_array('sale/saleall', session('action'))) {
                //渠道只能看自己的
                $where['user_name'] = ['like', session('username')];
            }
            //公众号
            if (isset($param['searchAccount']) && !empty($param['searchAccount'])) {
                $where['account'] = ['like', '%' . $param['searchAccount'] . '%'];
            }

            if (isset($param['searchStartDate']) && !empty($param['searchStartDate'])
                && isset($param['searchEndDate']) && !empty($param['searchEndDate'])
            ) {
                //有开始日期有结束日期
                $where['datepicker'] = ['between time', [$param['searchStartDate'], $param['searchEndDate']]];
            } else if (isset($param['searchStartDate']) && !empty($param['searchStartDate'])
                && (!isset($param['searchEndDate']) || empty($param['searchEndDate']))
            ) {
                //有开始日期无结束日期
                $where['datepicker'] = ['>= time', $param['searchStartDate']];
            } else if ((!isset($param['searchStartDate']) || empty($param['searchStartDate']))
                && isset($param['searchEndDate']) && !empty($param['searchEndDate'])
            ) {
                //无开始日期有结束日期
                $where['datepicker'] = ['<= time', $param['searchEndDate']];
            }

            $selectResult = db('putorder')->where($where)->limit($offset, $limit)->order('id desc')->select();

            cache('sale' . session('username'), $selectResult);

            $totalPrice = 0;
            $totalDealPrice = 0;

            foreach ($selectResult as $key => $vo) {
                $totalPrice += $vo['price'];
                $totalDealPrice += $vo['deal_price'];

                switch ($vo['source']) {
                    case 1:
                        $selectResult[$key]['source'] = '纽狮下单';
                        break;
                    case 2:
                        $selectResult[$key]['source'] = '报系下单';
                        break;
                    default:
                        $selectResult[$key]['source'] = '未定义';
                        break;
                }

                switch ($vo['content']) {
                    case 1:
                        $selectResult[$key]['content'] = '微信贴片';
                        break;
                    case 2:
                        $selectResult[$key]['content'] = '微信软文';
                        break;
                    default:
                        $selectResult[$key]['content'] = '未定义';
                        break;
                }

                //节约空间，把它们拼成两行
                $selectResult[$key]['contact'] = $vo['contact'] . '<br>' . $vo['phone'];
                $selectResult[$key]['serv_name'] = $vo['serv_name'] . '<br>' . $vo['serv_phone'];
            }

            $selectResult[] = ['number' => '', 'source' => '', 'content' => '', 'account' => '', 'position' => '', 'datepicker' => '', 'contact' => '', 'serv_name' => '合计：', 'price' => $totalPrice, 'deal_price' => $totalDealPrice];

            $return['total'] = db('putorder')->where($where)->count();  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        $this->assign(['start' => date("Y-m-d", strtotime("last month")),
            'end' => date("Y-m-d")]);
        return $this->fetch();
    }

    public function outExcel()
    {
        import("excel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("纽狮新媒体")
            ->setLastModifiedBy("纽狮新媒体")
            ->setTitle("销售表格")
            ->setSubject("销售数据")
            ->setDescription("")
            ->setKeywords("")
            ->setCategory("");

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('销售数据');

        // 加粗
        for ($i = 'A'; $i <= 'L'; $i++) {
            $objPHPExcel->getActiveSheet()->getStyle($i . '1')->getFont()->setBold(true);
        }

        //设置列宽
        for ($i = 'A'; $i <= 'L'; $i++) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($i)->setWidth('15');
        }

        $objPHPExcel->getActiveSheet()
            ->setCellValue('A1', '订单编号')
            ->setCellValue('B1', '订单来源')
            ->setCellValue('C1', '订单内容')
            ->setCellValue('D1', '账号')
            ->setCellValue('E1', '位置')
            ->setCellValue('F1', '时间')
            ->setCellValue('G1', '联系人')
            ->setCellValue('H1', '联系电话')
            ->setCellValue('I1', '服务支持')
            ->setCellValue('J1', '服务电话')
            ->setCellValue('K1', '订单价')
            ->setCellValue('L1', '结算价');

// Add some data
        $data = cache('sale' . session('username'));

        $totalPrice = 0;
        $totalDealPrice = 0;
        $maxRow = 2;

        foreach ($data as $key => $vo) {
            switch ($vo['source']) {
                case 1:
                    $vo['source'] = '纽狮下单';
                    break;
                case 2:
                    $vo['source'] = '报系下单';
                    break;
                default:
                    $vo['source'] = '未定义';
                    break;
            }

            switch ($vo['content']) {
                case 1:
                    $vo['content'] = '微信贴片';
                    break;
                case 2:
                    $vo['content'] = '微信软文';
                    break;
                default:
                    $vo['content'] = '未定义';
                    break;
            }

            $totalPrice += $vo['price'];
            $totalDealPrice += $vo['deal_price'];
            $maxRow = 2 + $key;

            $objPHPExcel->getActiveSheet()
                ->setCellValueExplicitByColumnAndRow(0, 2 + $key, $vo['number'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueByColumnAndRow(1, 2 + $key, $vo['source'])
                ->setCellValueByColumnAndRow(2, 2 + $key, $vo['content'])
                ->setCellValueByColumnAndRow(3, 2 + $key, $vo['account'])
                ->setCellValueByColumnAndRow(4, 2 + $key, $vo['position'])
                ->setCellValueByColumnAndRow(5, 2 + $key, $vo['datepicker'])
                ->setCellValueByColumnAndRow(6, 2 + $key, $vo['contact'])
                ->setCellValueByColumnAndRow(7, 2 + $key, $vo['phone'])
                ->setCellValueByColumnAndRow(8, 2 + $key, $vo['serv_name'])
                ->setCellValueByColumnAndRow(9, 2 + $key, $vo['serv_phone'])
                ->setCellValueByColumnAndRow(10, 2 + $key, $vo['price'])
                ->setCellValueByColumnAndRow(11, 2 + $key, $vo['deal_price']);
        }

        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, $maxRow + 1, '合计：')
            ->setCellValueByColumnAndRow(10, $maxRow + 1, $totalPrice)
            ->setCellValueByColumnAndRow(11, $maxRow + 1, $totalDealPrice);

// Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="销售数据.xlsx"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
}
